﻿Imports System.Linq
Imports System.Data
Imports System.Web
Imports Equipment.DataAccess

Partial Public Class Role

#Region "Properties"
    Private _db As EquipmentDataContext
    Public Property DBContext As EquipmentDataContext
        Get
            Return _db
        End Get
        Set(ByVal value As EquipmentDataContext)
            _db = value
        End Set
    End Property
#End Region

    Public Shared Function RetrieveAll() As IEnumerable(Of Role)
        Dim db As EquipmentDataContext = Database.Instance
        Return db.Roles.OrderBy(Function(ur) ur.Site.Description).ThenBy(Function(ur) ur.Description)
    End Function

    Public Shared Function RetrieveAllBySiteID(ByVal siteID As Integer) As IQueryable(Of Role)
        Dim db As EquipmentDataContext = Database.Instance
        Return From r In Database.Instance.Roles Where r.SiteID = siteID Order By r.Description
    End Function

    Public Shared Function GetByPrimaryKey(ByVal id As Integer) As Role
        Dim db As EquipmentDataContext = Database.Instance
        Dim result = From ug In db.Roles Where ug.ID = id
        Dim roleEntity As Role = result.FirstOrDefault()
        roleEntity.DBContext = db
        Return roleEntity
    End Function

    Public Shared Function Insert(ByVal siteID As Integer, ByVal description As String, ByVal statusString As String) As Role

        Dim _dataBase As EquipmentDataContext = Database.Instance
        Dim newRole As New Role

        newRole.Description = description
        newRole.SiteID = siteID
        newRole.PageAccess = statusString

        _dataBase.Roles.InsertOnSubmit(newRole)
        Try
            _dataBase.SubmitChanges()
        Catch ex As Exception
            ' logger.Error(exception.Message + ":" + exception.StackTrace);
        End Try
        Return newRole
    End Function

    Public Sub Save()
        If Me.DBContext IsNot Nothing Then
            Dim _dataBase As EquipmentDataContext = Me.DBContext

            Try
                _dataBase.SubmitChanges()
            Catch ex As Exception
                ' logger.Error(exception.Message + ":" + exception.StackTrace);
            End Try
        End If

    End Sub
End Class
